package com.uzai.console.service.wxqsuperadmin.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.enums.MerConfigTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.cms.base.CmsBaseInfoDto;
import com.uzai.console.dto.wxqsuperadmin.WxqSuperAdminConfigDto;
import com.uzai.console.dto.wxqsuperadmin.WxqSuperAdminDto;
import com.uzai.console.dto.wxqsuperadmin.WxqSuperAdminIdDto;
import com.uzai.console.dto.wxqsuperadmin.WxqSuperAdminQuery;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.es.EsWorkWxGroupInfo;
import com.uzai.console.entity.es.EsWorkWxGroupMember;
import com.uzai.console.entity.es.EsWxGroupMember;
import com.uzai.console.entity.es.WxqSuperAdmin;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.wxqsuperadmin.WxqSuperAdminService;
import com.uzai.console.vo.cms.base.CmsBaseInfoVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroup.WxGroupInfoVo;
import com.uzai.console.vo.wxqsuperadmin.WxqSuperAdminConfigVo;
import com.uzai.console.vo.wxqsuperadmin.WxqSuperAdminVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WxqSuperAdminServiceImpl implements WxqSuperAdminService {

    Logger logger = LoggerFactory.getLogger(WxqSuperAdminServiceImpl.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询社群超级管理员列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqSuperAdminQuery
     * @return null
     */
    public Page<WxqSuperAdminVo> findByPage(WxqSuperAdminQuery wxqSuperAdminQuery){
        //新建返回到页面的LIST对象
        List<WxqSuperAdminVo> wxqSuperAdminVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxqSuperAdminVo> page = new Page<>();
        wxqSuperAdminQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxqSuperAdminQuery.getMerId())));


        //管理员类型(0-群内超级管理员 1-所有群超级管理员)
        if(wxqSuperAdminQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type", wxqSuperAdminQuery.getType()));
        }

        //群微信id
        if(StringUtils.isNotBlank(wxqSuperAdminQuery.getGroupWxid())){
            boolQuery.must(QueryBuilders.termQuery("groupWxid", wxqSuperAdminQuery.getGroupWxid()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxqSuperAdminQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid", wxqSuperAdminQuery.getWxid()));
        }

        //机器人类型
        if(StringUtils.isNotBlank(wxqSuperAdminQuery.getDeviceType())){
            boolQuery.must(QueryBuilders.termQuery("deviceType", wxqSuperAdminQuery.getDeviceType()));
        }

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        //查询群存不存在
        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WXQ_SUPER_ADMIN, searchSourceBuilder, wxqSuperAdminQuery.getSize(), wxqSuperAdminQuery.getFromIndex(), null, null, highlightField, wxqSuperAdminQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxqSuperAdmin wxqSuperAdmin  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxqSuperAdmin.class);
                if(wxqSuperAdmin != null){
                    WxqSuperAdminVo wxqSuperAdminVo = new WxqSuperAdminVo();
                    BeanUtils.copyProperties(wxqSuperAdmin, wxqSuperAdminVo);

                    if(wxqSuperAdminVo.getDeviceUniqueId() != null){
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqSuperAdminVo.getDeviceUniqueId(), wxqSuperAdminVo.getDeviceType(), wxqSuperAdminVo.getMerId());
                        if(device != null){
                            wxqSuperAdminVo.setDeviceName(device.getDeviceName());
                            wxqSuperAdminVo.setDeviceRemark(device.getDeviceRemark());
                        }
                    }

                    //群wxid不为空，则需要查询群成员
                    if(StringUtils.isNotBlank(wxqSuperAdmin.getGroupWxid())){
                        //个人微信
                        if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(wxqSuperAdmin.getDeviceType())){
                            //群成员id：merId_groupWxid_wxid
                            String id = wxqSuperAdmin.getMerId() + "_" + wxqSuperAdmin.getGroupWxid() + "_" + wxqSuperAdmin.getWxid();
                            //通过查询运营商其他索引分片获取分片索引
                            String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxqSuperAdmin.getMerId());
                            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, id, null);
                            EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
                            if(esWxGroupMember != null){
                                wxqSuperAdminVo.setNick(esWxGroupMember.getNick());
                                wxqSuperAdminVo.setHimg(esWxGroupMember.getHimg());
                            }
                        }else{//企业微信
                            //群成员id：merId_groupWxid_wxid
                            String id = wxqSuperAdmin.getMerId() + "_" + wxqSuperAdmin.getGroupWxid() + "_" + wxqSuperAdmin.getWxid();
                            //通过查询运营商其他索引分片获取分片索引
                            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxqSuperAdmin.getMerId());
                            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, id, null);
                            EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
                            if(esWorkWxGroupMember != null){
                                wxqSuperAdminVo.setNick(esWorkWxGroupMember.getNick());
                                wxqSuperAdminVo.setHimg(esWorkWxGroupMember.getHimg());
                            }
                        }
                    }
                    wxqSuperAdminVoList.add(wxqSuperAdminVo);
                }
            }
        }
        //返回到页面分页对象
        page.setRecords(wxqSuperAdminVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 添加超级管理员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqSuperAdminDto
     * @return null
     */
    @Transactional
    public void add(WxqSuperAdminDto wxqSuperAdminDto){

        if(wxqSuperAdminDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入管理员类型");
        }

        if(StringUtils.isBlank(wxqSuperAdminDto.getDeviceType())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人类型");
        }

        //临时封装成员wxid
        List<String> wxidList = wxqSuperAdminDto.getWxidList();
        if(wxidList == null){
            wxidList = new ArrayList<>();
        }

        //选择的会员
        List<String> idList = wxqSuperAdminDto.getIdList();
        if(idList == null){
            idList = new ArrayList<>();
        }

        String wxqSuperAdminId = "";
        String groupWxid = null;
        String groupName = null;
        Long deviceUniqueId = null;
        String deviceId = null;
        if(wxqSuperAdminDto.getType().intValue() == 0){ //群内管理员
            if(StringUtils.isBlank(wxqSuperAdminDto.getGroupId())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群id");
            }

            //个人微信
            if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(wxqSuperAdminDto.getDeviceType())){
                //查询群存不存在
                String esName = EsIndexName.UZAI_WX_CONTACTS;
                String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxqSuperAdminDto.getMerId());
                Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, wxqSuperAdminDto.getGroupId(), null);
                WxGroupInfoVo wxGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxGroupInfoVo.class);
                if(wxGroupInfoVo == null){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群不存在");
                }
                wxqSuperAdminId = wxGroupInfoVo.getId();
                groupWxid = wxGroupInfoVo.getWxid();
                groupName = wxGroupInfoVo.getNick();
                deviceUniqueId = wxGroupInfoVo.getDeviceUniqueId();
                deviceId = wxGroupInfoVo.getDeviceId();

                //通过查询运营商其他索引分片获取分片索引
                String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxqSuperAdminDto.getMerId());
                for (String memberId : idList) {
                    Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, memberId, null);
                    EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
                    if(esWxGroupMember != null){
                        wxidList.add(esWxGroupMember.getWxid());
                    }
                }

            }else{//企业微信
                //查询群存不存在
                String esName = EsIndexName.UZAI_WORKWX_GROUP_INFO;
                String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(esName, wxqSuperAdminDto.getMerId());
                //查询微信群
                Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxqSuperAdminDto.getGroupId(), null);
                EsWorkWxGroupInfo esWorkWxGroupInfo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
                if(esWorkWxGroupInfo == null){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群不存在");
                }
                wxqSuperAdminId = esWorkWxGroupInfo.getId();
                groupWxid = esWorkWxGroupInfo.getGroupId();
                groupName = esWorkWxGroupInfo.getNickName();
                deviceUniqueId = esWorkWxGroupInfo.getDeviceUniqueId();
                deviceId = esWorkWxGroupInfo.getDeviceId();

                //通过查询运营商其他索引分片获取分片索引
                String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxqSuperAdminDto.getMerId());
                for (String memberId : idList) {
                    Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, memberId, null);
                    EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
                    if(esWorkWxGroupMember != null){
                        wxidList.add(esWorkWxGroupMember.getWxid());
                    }
                }
            }
        }else{ //所有群管理员
            wxqSuperAdminId = wxqSuperAdminDto.getMerId() + "_all_all";
        }

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入成员");
        }

        for (String wxid : wxidList) {
            String id = wxqSuperAdminId + "_" + wxid;
            Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, id, null);
            if(map != null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, wxid+"已经在管理员中");
            }
        }

        for (String wxid : wxidList) {

            String id = wxqSuperAdminId + "_" + wxid;

            WxqSuperAdmin wxqSuperAdmin = new WxqSuperAdmin();

            Integer now = DateUtil.getNowTime();
            wxqSuperAdmin.setId(id);
            wxqSuperAdmin.setMerId(wxqSuperAdminDto.getMerId());
            wxqSuperAdmin.setGroupWxid(groupWxid);
            wxqSuperAdmin.setGroupName(groupName);
            wxqSuperAdmin.setDeviceType(wxqSuperAdminDto.getDeviceType());
            wxqSuperAdmin.setDeviceUniqueId(deviceUniqueId);
            wxqSuperAdmin.setDeviceId(deviceId);
            wxqSuperAdmin.setWxid(wxid);
            wxqSuperAdmin.setRemark(wxqSuperAdminDto.getRemark());
            wxqSuperAdmin.setType(wxqSuperAdminDto.getType());
            wxqSuperAdmin.setCreateTime(now);
            wxqSuperAdmin.setUpdateTime(now);
            elasticsearchUtil.addData(wxqSuperAdmin, EsIndexName.UZAI_WXQ_SUPER_ADMIN, id);
        }

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 删除管理员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqSuperAdminIdDto
     * @return null
     */
    @Transactional
    public void deleteById(WxqSuperAdminIdDto wxqSuperAdminIdDto){

        if(StringUtils.isBlank(wxqSuperAdminIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, wxqSuperAdminIdDto.getId(), null);
        WxqSuperAdmin wxqSuperAdmin  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqSuperAdmin.class);
        if(wxqSuperAdmin == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该管理员不存在");
        }

        //删除管理员
        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, wxqSuperAdminIdDto.getId());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 查询超级管理员详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqSuperAdminIdDto
     * @return null
     */
    public WxqSuperAdminVo findById(WxqSuperAdminIdDto wxqSuperAdminIdDto){
        if(StringUtils.isBlank(wxqSuperAdminIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, wxqSuperAdminIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该超级管理员不存在");
        }

        WxqSuperAdmin wxqSuperAdmin  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqSuperAdmin.class);
        WxqSuperAdminVo wxqSuperAdminVo = new WxqSuperAdminVo();
        BeanUtils.copyProperties(wxqSuperAdmin, wxqSuperAdminVo);

        if(wxqSuperAdminVo.getDeviceUniqueId() != null){
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqSuperAdminVo.getDeviceUniqueId(), wxqSuperAdminVo.getDeviceType(), wxqSuperAdminVo.getMerId());
            if(device != null){
                wxqSuperAdminVo.setDeviceName(device.getDeviceName());
                wxqSuperAdminVo.setDeviceRemark(device.getDeviceRemark());
            }
        }

        return wxqSuperAdminVo;
    }

    /**
     * 查询社群超级管理员配置信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return CmsBaseInfoVo
     */
    public WxqSuperAdminConfigVo findConfig(WxqSuperAdminConfigDto wxqSuperAdminConfigDto){

        //社群类型
        if(StringUtils.isBlank(wxqSuperAdminConfigDto.getDeviceType())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入社群类型");
        }

        WxqSuperAdminConfigVo wxqSuperAdminConfigVo = new WxqSuperAdminConfigVo();

        //默认个人微信
        String wxq_super_admin_config = MerConfigKeyEnum.WECHAT_WXQ_SUPER_ADMIN_CONFIG.getValue();
        if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(wxqSuperAdminConfigDto.getDeviceType())){//企业微信
            wxq_super_admin_config = MerConfigKeyEnum.WXWORK_WXQ_SUPER_ADMIN_CONFIG.getValue();
        }

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(wxqSuperAdminConfigDto.getMerId(), wxq_super_admin_config);
        if (merBaseConfig != null) {
            wxqSuperAdminConfigVo = JSONObject.parseObject(merBaseConfig.getVal(), WxqSuperAdminConfigVo.class);
        }

        return wxqSuperAdminConfigVo;
    }

    /**
     * 修改社群超级管理员配置信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void updateConfig(WxqSuperAdminConfigDto wxqSuperAdminConfigDto){

        //社群类型
        if(StringUtils.isBlank(wxqSuperAdminConfigDto.getDeviceType())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入社群类型");
        }

        WxqSuperAdminConfigVo wxqSuperAdminConfigVo = new WxqSuperAdminConfigVo();
        BeanUtils.copyProperties(wxqSuperAdminConfigDto, wxqSuperAdminConfigVo);

        //默认个人微信
        String wxq_super_admin_config = MerConfigKeyEnum.WECHAT_WXQ_SUPER_ADMIN_CONFIG.getValue();
        if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(wxqSuperAdminConfigDto.getDeviceType())){//企业微信
            wxq_super_admin_config = MerConfigKeyEnum.WXWORK_WXQ_SUPER_ADMIN_CONFIG.getValue();
        }

        //默认个人微信
        String redis_wxq_super_admin_config = RedisCacheKeyEnum.WECHAT_WXQ_SUPER_ADMIN_CONFIG.getKey();
        if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(wxqSuperAdminConfigDto.getDeviceType())){//企业微信
            redis_wxq_super_admin_config = RedisCacheKeyEnum.WXWORK_WXQ_SUPER_ADMIN_CONFIG.getKey();
        }

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(wxqSuperAdminConfigDto.getMerId(), wxq_super_admin_config);
        Integer now = DateUtil.getNowTime();
        //修改
        if (merBaseConfig != null){
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(wxqSuperAdminConfigVo)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        } else { //增加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(wxqSuperAdminConfigDto.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(wxq_super_admin_config);
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(wxqSuperAdminConfigVo)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }

        //保存到Redis当中
        redisTemplate.opsForValue().set(String.format(redis_wxq_super_admin_config, wxqSuperAdminConfigDto.getMerId()), merBaseConfig.getVal());
    }
}
